package com.kbt.adapter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.google.gson.Gson;
import com.kbt.activity.AddressAddActivity;
import com.kbt.activity.AddressMangeActivity;
import com.kbt.activity.GoodForPayActivity;
import com.kbt.activity.R;
import com.kbt.commont.Constants;
import com.kbt.model.data.AddressBean;
import com.kbt.model.data.BaseBean;
import com.kbt.model.data.ShopCarBean;
import com.kbt.model.data.UserAddressInfoModel;
import com.kbt.model.holder.UserAddressInfoHolder;
import com.kbt.net.RequestManager;
import com.kbt.util.data.StaticData;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.Utils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhgk
 * @package: com.kbt.adapter
 * @TODO: 收货地址适配器
 * @data: 2015/8/14 16:37
 * @version: V1.0
 */
public class AddressForMangerAdapter extends BaseAdapter implements RequestManager.ResponseInterface {

    //商品数据列表
    private List<AddressBean> addressInfoModleList;
    //生命上下文
    private Activity context;
    private RequestManager mRequestManager;
    private Map<String, String> map = null;
    private BaseBean baseBean;
    private int posi;
    private SharePreferenceUtils share;

    public AddressForMangerAdapter(Activity context, List<AddressBean> addressInfoModleList) {
        this.addressInfoModleList = addressInfoModleList;
        this.context = context;
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        map = new HashMap<String, String>();
        share = new SharePreferenceUtils(context);
    }

    @Override
    public int getCount() {
        return addressInfoModleList.size();
    }

    @Override
    public Object getItem(int position) {
        return addressInfoModleList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * 再次赋值
     *
     * @param mlist
     */
    public void setList(List<AddressBean> mlist) {
        addressInfoModleList = mlist;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {


        UserAddressInfoHolder itemHolder;

        if (convertView == null) {
            itemHolder = new UserAddressInfoHolder();

            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(R.layout.address_item, null);
            itemHolder.setUserInfoLayout((LinearLayout) convertView.findViewById(R.id.userInfoLayout));
            itemHolder.setCheckBtn((RadioButton) convertView.findViewById(R.id.checkBtn));

            itemHolder.setDelBtn((ImageView) convertView.findViewById(R.id.delBtn));

            itemHolder.setUserNameView((TextView) convertView.findViewById(R.id.userName));
            itemHolder.setUserMobileView((TextView) convertView.findViewById(R.id.userPhone));
            itemHolder.setUserAddressInfoView((TextView) convertView.findViewById(R.id.address));

            convertView.setTag(itemHolder);
        } else {
            itemHolder = (UserAddressInfoHolder) convertView.getTag();
        }
        AddressBean addressInfo = addressInfoModleList.get(position);
        if (addressInfo.getIs_default_address() == 1) {
            itemHolder.getCheckBtn().setChecked(true);
        } else {
            itemHolder.getCheckBtn().setChecked(false);
        }
        // itemHolder.getCheckBtn().setSelected(addressInfo.isDeafultAddress());
        itemHolder.getUserNameView().setText(addressInfo.getUser_name());
        itemHolder.getUserMobileView().setText(addressInfo.getUser_mobile());
        itemHolder.getUserAddressInfoView().setText(addressInfo.getUser_address_sxq() + " " + addressInfo.getUser_address_info());


        //选择按钮事件
        itemHolder.getCheckBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (((RadioButton) v).isChecked()) {
                    updateAddressInfoModleList(position);
                }
            }
        });

        //删除按钮事件
        itemHolder.getDelBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                posi = position;
                map.clear();
                map.put("methodType", "remove");
                Gson gson = new Gson();
                Map dataMap = new HashMap<String,String>();
                dataMap.put("address_id", addressInfoModleList.get(position).getAddress_id());
                map.put("data", gson.toJson(dataMap));
                mRequestManager.post(Constants.ServiceInterFace.deleteAddressURL, map, Constants.RequestTag.deleteAddressTag, BaseBean.class);
            }
        });
        if(AddressMangeActivity.tag!=null&&AddressMangeActivity.tag.equals("1")) {
            //返回订单页面
            itemHolder.getUserInfoLayout().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //返回选中的地址
                    Intent intent = new Intent(context, GoodForPayActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("address", addressInfoModleList.get(position));
                    intent.putExtras(bundle);
                    intent.putExtra("list", (Serializable) AddressMangeActivity.goodInfoList);
                    intent.putExtra("biaoji", AddressMangeActivity.biaoji);
                    if(AddressMangeActivity.order_jf_sub_je!=null&&!"".equals(AddressMangeActivity.order_jf_sub_je)){
                        intent.putExtra("order_jf_sub_je",AddressMangeActivity.order_jf_sub_je);
                    }
                    context.startActivity(intent);
                    context.finish();
                }
            });
        }

        return convertView;

    }

    //改变默认地址
    private void updateAddressInfoModleList(int position) {
       if(Utils.isNetworkAvailable(context)) {
           posi = position;
           map.clear();
           map.put("methodType", "set_default");
           Gson gson = new Gson();
           Map dataMap = new HashMap<String,String>();
           dataMap.put("address_id", addressInfoModleList.get(position).getAddress_id());
           dataMap.put("create_user_mobile", share.getString("user_mobile", ""));
           map.put("data", gson.toJson(dataMap));
           mRequestManager.post(Constants.ServiceInterFace.setDefaultAddressURL, map, Constants.RequestTag.setDefaultAddress2Tag, BaseBean.class);
       }else {
           Toast.makeText(context, R.string.Wangluo, Toast.LENGTH_SHORT).show();
       }
    }

    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        if (tag == Constants.RequestTag.deleteAddressTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {
                    //删除数据，通知适配器变化
                    AddressBean temp = addressInfoModleList.get(posi);
                    if (temp.getIs_default_address() == 1 && addressInfoModleList.size() > 1) {
                        addressInfoModleList.remove(posi);
                        //设置默认
                        httpSetDefault();
                    } else {
                        addressInfoModleList.remove(posi);
                        notifyDataSetChanged();
                    }
                } else {
                    Toast.makeText(context, "" + baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.setDefaultAddressTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {
//                    addressInfoModleList.remove(posi);
                    addressInfoModleList.get(0).setIs_default_address(1);
                    notifyDataSetChanged();
                } else {
                    Toast.makeText(context, "" + baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.setDefaultAddress2Tag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {

                    AddressBean infoModle;
                    for (int i = 0; i < addressInfoModleList.size(); i++) {
                        infoModle = addressInfoModleList.get(i);
                        if (i == posi) {
                            infoModle.setIs_default_address(1);
                        } else {
                            infoModle.setIs_default_address(0);
                        }
                    }
                    notifyDataSetChanged();
                } else {
                    Toast.makeText(context, "" + baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        Toast.makeText(context, R.string.noWangluo, Toast.LENGTH_SHORT).show();
    }

    //地址设置默认
    public void httpSetDefault() {
       if(Utils.isNetworkAvailable(context)){
        map.clear();
        map.put("methodType", "set_default");
        Gson gson = new Gson();
        Map dataMap = new HashMap<String,String>();
        dataMap.put("address_id", addressInfoModleList.get(0).getAddress_id());
        dataMap.put("create_user_mobile", share.getString("user_mobile",""));
        map.put("data", gson.toJson(dataMap));
        mRequestManager.post(Constants.ServiceInterFace.setDefaultAddressURL, map, Constants.RequestTag.setDefaultAddressTag, BaseBean.class);
       }else{
           Toast.makeText(context,R.string.Wangluo,Toast.LENGTH_SHORT).show();
       }
    }
}
